<template>
  <view class="login-box">
    <view class="login-icons">
      <uni-icons type="contact-filled" size="120" color="#AFAFAF"></uni-icons>
    </view>
    <button type="primary" class="login-button" @click="getUserInfo">一键登录</button>
    <view class="login-text">
      登录后尽享更多权益
    </view>
  </view>
</template>

<script>
  import {mapState,mapMutations} from "vuex"
  export default {
    name: "my-login",
    computed:{
      ...mapState('m_user',['userinfo','redirectInfo'])
    },
    data() {
      return {

      };
    },
    methods: {
      ...mapMutations("m_user", ['updateUserinfo','updateToken','updatePage']),
    getUserInfo() {
       uni.getUserProfile({
          desc: "您的授权信息",
          success:(res) =>{
            this.updateUserinfo(res.userInfo)
            console.log(res);
            this.getToken(res)
          },
          fail: (res) => {
            return uni.$showMsg('您取消了登录授权')
          }
        })
      },
      navigateBack(){
        if(this.redirectInfo&&this.redirectInfo.openType=="switchTab"){
          uni.switchTab({
            url:this.redirectInfo.from,
            complete:()=>{
              this.updatePage('')
            }
          })
        }
      },
    async  getToken(info){
        const[ err,res]=await uni.login().catch(err=>err)
        if(err||res.errMsg!="login:ok") return uni.$showMsg('登录失败╭（╯_╰）╭')
        console.log(res);
        const query={
          code:res.code,
          encryptedData:info.encryptedData,
          iv:info.iv,
          rawData:info.rawData,
          signature:info.signature,
        }
        const {data:result} = await uni.$http.post('/api/public/v1/users/wxlogin',query)
        if(result.meta.status==200) return uni.$showMsg('登录失败╭（╯_╰）╭')
        uni.$showMsg('登录成功*\(^_^)/*')
        this.updateToken('Bearer eyJhbGciOiJIUzl1NilslnR5cCI6lkpXVCJ9.eyJ1aWQiOjM1LCJpYXQiOjE1OTg4NjY0NTlslmV4cCI6MTAwMTU5ODg2NjQ1MX0.8hg6C7spbNrs87YECTLzPgGJZ1Ho39Su8r6D3KOTzUE')
        this.navigateBack()
      }
    }
  }
</script>

<style lang="scss">
  .login-box {
    height: 750rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background-color: #fff;
    position: relative;

    &::after {
      content: '';
      display: block;
      width: 100%;
      height: 50px;
      background-color: #c00000;
      position: absolute;
      right: 0;
      bottom: 0;
      border-radius: 100%;
      transform: translateY(50%);
      background-color: #f5f5f5;
    }

    .login-button {
      width: 90%;
      background-color: #c00000;
      border-radius: 50px;
      margin: 15px 0;
    }

    .login-text {
      font-size: 13px;
      color: gray;
    }
  }
</style>
